import * as path from "path";
import * as fs from "fs";
import packager from "electron-packager";
import { build, Platform, Configuration } from "electron-builder";
import minimist from "minimist";
import { execSync } from "child_process";
import { version, description, devDependencies } from "../package.json";

async function packageLinuxMips64el() {
    try {
        const [unpacked] = await packager({
            dir: path.resolve(__dirname, ".."),
            electronVersion: "10.1.0",
            platform: "linux",
            arch: "mips64el",
            appVersion: version,
            executableName: "AnyShare",
            out: path.resolve(__dirname, "../release"),
            icon: path.resolve(__dirname, "../resources/common/icon.png"),
            asar: true,
            overwrite: true,
            ignore: /^\/(?!(node_modules|devtools|build|public|resources|package\.json))/,
            prune: true,
            appCopyright: `版权所有 © 2011-${new Date().getFullYear()} 上海爱数信息技术股份有限公司`,
        });

        // eslint-disable-next-line
        const installer = require("electron-installer-redhat");
        await installer({
            src: unpacked,
            dest: path.resolve(__dirname, "../release"),
            arch: "mips64el",
            description,
            icon: path.resolve(__dirname, "../resources/common/icon.png"),
            execArguments: ["--no-sandbox --js-flags=--noexpose_wasm"],
            name: "AnyShare",
        });
        const debinstaller = require("electron-installer-debian");
        await debinstaller({
            src: unpacked,
            dest: path.resolve(__dirname, "../release"),
            arch: "mips64el",
            icon: path.resolve(__dirname, "../resources/common/icon.png"),
            execArguments: ["--no-sandbox --js-flags=--noexpose_wasm"],
            description,
            name: "AnyShare",
        });
    } catch (e) {
        console.error(e);
    }
}

async function packageLinux(config: Configuration, files: string[]) {
    execSync(`cp  ${path.resolve(__dirname, "../package.json")}  ${path.resolve(__dirname, "../packageold.json")}`);
    execSync(`mv  ${path.resolve(__dirname, "../package.json")}  ${path.resolve(__dirname, "../backup.json")}`);
    const packageJson = require("../backup.json");
    packageJson.name = "AnyShare";
    packageJson.author = "AISHU Software, Inc.";
    const devDependencies = Object.assign(packageJson.devDependencies, packageJson.dependencies);
    packageJson.devDependencies = devDependencies;
    packageJson.dependencies = {};
    fs.writeFileSync("package.json", JSON.stringify(packageJson, null, 2));
    execSync(`rm -rf  ${path.resolve(__dirname, "../build/static/foxit")}`);

    await build({
        targets: Platform.LINUX.createTarget(),
        config: { ...config, files: [...files, "resources/linux"] },
    });

    // PackageLinuxMips64el
    const mipsPackageJson = require("../packageold.json");
    mipsPackageJson.author = "AISHU Software, Inc.";
    mipsPackageJson.devDependencies.electron = "10.1.0";
    fs.writeFileSync("package.json", JSON.stringify(mipsPackageJson, null, 2));

    execSync(
        `cd ${path.resolve(
            __dirname,
            "../../.."
        )} && yarn --registry http://repository.aishu.cn:8081/repository/npm-all`
    );

    try {
        execSync(`cd ${path.resolve(__dirname, "../../..")} && yarn build-all`);
    } catch (e) {
        console.log(e);
    }

    execSync(`cd ${path.resolve(__dirname, "../../..")} && yarn workspace @anyshare/electron build-main`);

    execSync(`rm -rf  ${path.resolve(__dirname, "../packageold.json")}`);

    execSync(
        `mv  ${path.resolve(__dirname, "../../../package.json")}  ${path.resolve(__dirname, "../../../backup.json")}`
    );
    const anyShareJson = require("../../../backup.json");
    anyShareJson.workspaces = [
        "applications/web/*",
        "applications/webservice/*",
        "applications/oauth2/*",
        "package/*",
        "locales/*",
    ];
    fs.writeFileSync(path.resolve(__dirname, "../../../package.json"), JSON.stringify(anyShareJson, null, 2));

    const thePackageJson = require("../backup.json");
    thePackageJson.name = "AnyShare";
    thePackageJson.author = "AISHU Software, Inc.";
    const theDevDependencies = Object.assign(thePackageJson.devDependencies, thePackageJson.dependencies);
    thePackageJson.devDependencies = theDevDependencies;
    thePackageJson.dependencies = {};
    fs.writeFileSync("package.json", JSON.stringify(thePackageJson, null, 2));
    execSync(`rm -rf  ${path.resolve(__dirname, "../build/static/foxit")}`);

    execSync(
        `cd ${path.resolve(__dirname, "../")} && yarn --registry http://repository.aishu.cn:8081/repository/npm-all`
    );

    await packageLinuxMips64el();

    execSync(`mv  ${path.resolve(__dirname, "../backup.json")}  ${path.resolve(__dirname, "../package.json")}`);
    execSync(
        `mv  ${path.resolve(__dirname, "../../../backup.json")}  ${path.resolve(__dirname, "../../../package.json")}`
    );
}

async function packageAll() {
    const argv = minimist<{ platform: string; debug: string }>(process.argv.slice(2));

    const platform = argv.platform || "all";

    const files = ["devtools", "build", "public", "resources/common"];

    const config: Configuration = {
        appId: `com.aishu.anyshare`,
        icon: path.resolve(__dirname, "../resources/common/icon.png"),
        productName: `AnyShare`,
        // eslint-disable-next-line
        artifactName: "${productName}-${platform}-${arch}-${version}.${ext}",
        copyright: `版权所有 © 2011-${new Date().getFullYear()} 上海爱数信息技术股份有限公司`,
        electronVersion: devDependencies.electron,
        directories: {
            buildResources: "resources",
            output: "release",
        },
        dmg: {
            contents: [
                {
                    x: 140,
                    y: 180,
                },
                {
                    x: 420,
                    y: 180,
                    type: "link" as const,
                    path: "/Applications",
                },
            ],
            icon: path.resolve(__dirname, "../resources/darwin/icon.icns"),
            background: path.resolve(__dirname, "../resources/darwin/background.png"),
            title: "AnyShare",
        },
        win: {
            target: [
                {
                    target: "nsis",
                    arch: ["x64"],
                },
            ],
            icon: path.resolve(__dirname, "../resources/win32/icon.ico"),
        },
        linux: {
            target: [
                {
                    target: "appimage",
                    arch: ["arm64", "x64"],
                },
                {
                    target: "deb",
                    arch: ["arm64", "x64"],
                },
                {
                    target: "rpm",
                    arch: ["arm64", "x64"],
                },
            ],
            executableName: "AnyShare",
            icon: path.resolve(__dirname, "../resources/linux/icon"),
            maintainer: "上海爱数信息技术股份有限公司",
            category: "Utility",
        },
        mac: {
            target: ["dmg", "zip"],
            icon: path.resolve(__dirname, "../resources/darwin/icon.icns"),
        },
        deb: {
            depends: ["libgconf-2-4"],
        },
        nsis: {
            oneClick: false,
        },
        nodeGypRebuild: false,
        buildDependenciesFromSource: false,
        npmRebuild: false,
        asar: true,
        protocols: [
            {
                name: "anyshare7",
                schemes: ["anyshare7"],
            },
        ],
    };

    if (argv.debug) {
        process.env.DEBUG = "electron-builder";
    }

    if (process.platform === "win32" && ["win", "win32", "all"].includes(platform)) {
        editPackageJson();
        await build({
            targets: Platform.WINDOWS.createTarget(),
            config: { ...config, files: [...files, "resources/win32"] },
        });
        revertPackageJson();
    }

    if (process.platform === "linux" && ["linux", "all"].includes(platform)) {
        packageLinux(config, files);
    }

    if (process.platform === "darwin" && ["mac", "all"].includes(platform)) {
        editPackageJson();
        await build({
            targets: Platform.MAC.createTarget(),
            config: { ...config, files: [...files, "resources/darwin"] },
        });
        revertPackageJson();
    }
}

packageAll();

function editPackageJson() {
    execSync(`mv  ${path.resolve(__dirname, "../package.json")}  ${path.resolve(__dirname, "../backup.json")}`);
    const packageJson = require("../backup.json");
    packageJson.name = "AnyShare";
    const devDependencies = Object.assign(packageJson.devDependencies, packageJson.dependencies);
    packageJson.devDependencies = devDependencies;
    packageJson.dependencies = {};
    fs.writeFileSync("package.json", JSON.stringify(packageJson, null, 2));
    execSync(`rm -rf  ${path.resolve(__dirname, "../build/static/foxit")}`);
}

function revertPackageJson() {
    execSync(`mv  ${path.resolve(__dirname, "../backup.json")}  ${path.resolve(__dirname, "../package.json")}`);
}
